﻿#include "qgroupchat.h"
#include "ui_qgroupchat.h"
#include "expressionui.h"
#include "mainui.h"
#include "login.h"


QGroupChat::QGroupChat(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::QGroupChat)
{
    ui->setupUi(this);
    m_count=0;
    m_num=0;
    setWindowTitle("群聊");
    ui->group_name_2->setEnabled(false);
    ui->textBrowser_2->setText("这里是劫哥的私人厨房,吃啥先汇报,做了没吃完后果自负！！！");
    ui->tbtn_close->hide();
    ui->tbtn_min->hide();
    connect(&m_timer,&QTimer::timeout,this,&QGroupChat::OnStartFileTrans);
    m_sock.connectToHost("192.168.43.91",10086);
    connect(&m_sock,&QTcpSocket::connected,[=](){
        qDebug()<<"群文件sock连接上服务器";
    });
}

QGroupChat::~QGroupChat()
{
    m_sock.disconnectFromHost();
    delete ui;
}

QString QGroupChat::getGroupName()
{
    return ui->group_name->text();
}

void QGroupChat::setGroupName(QString name)
{
    QString recvobj2 = name;//获取群账号
    int i = recvobj2.indexOf('(');
    recvobj2 =recvobj2.replace(")","");
    recvobj2 = recvobj2.mid(i+1);
    m_gid = recvobj2;
    ui->group_name->setText(name);
}

void QGroupChat::loadGroupPerson(QString name, QString head, int n)
{
    QString nickname = OpDb::getInstance().getNickName(name);
    QString text = nickname + "(" + name + ")";
    if(n==1)
    {
        QIcon icon(head);
        QListWidgetItem* item = new QListWidgetItem(icon,text);
        item->setBackground(QColor(255,255,255));
        ui->listWidget->addItem(item);
        m_num++;
    }
    else
    {
        QIcon icon(head);
        QListWidgetItem* item = new QListWidgetItem(icon,text);
        item->setBackground(QColor(200,200,200));
        ui->listWidget->addItem(item);
    }
    m_count++;
    QString str = QString("群成员%1/%2").arg(m_num).arg(m_count);
    ui->group_person->setText(str);
}

QPixmap QGroupChat::PixmapToRound(const QPixmap &src, const int &radius)
{
    if (src.isNull()) {
        return QPixmap();
    }
    QSize size(2*radius, 2*radius);
    //掩码图（黑白色）
    QBitmap mask(size);
    QPainter painter(&mask);
    //Antialiasing：反走样（抗锯齿）
    painter.setRenderHint(QPainter::Antialiasing);
    //SmoothPixmapTransform：用来在对图片进行缩放时启用线性插值算法而不是最邻近算法
    painter.setRenderHint(QPainter::SmoothPixmapTransform);
    //填充矩形
    painter.fillRect(0, 0, size.width(), size.height(), Qt::white);
    //画刷
    painter.setBrush(QColor(0, 0, 0));
    //绘制圆角矩形
    painter.drawRoundedRect(0, 0, size.width(), size.height(), 190, 190);
    //自适应图片
    QPixmap image = src.scaled(size);
    //setMask：创建不规则窗口使用
    image.setMask(mask);
    return image;
}

QWidget *QGroupChat::CreateWidgetL_R(int i, QString name, QString data)
{
    QFont font1;
    font1.setFamily("Microsoft YaHei");
    font1.setPointSize(15);
    font1.setStyleStrategy(QFont::PreferAntialias);
    QWidget * widget = new QWidget();
    widget->setStyleSheet("background:rgba(0,0,0,0);");
    widget->setMaximumWidth(700);
    QHBoxLayout *horLayout = new QHBoxLayout();//水平布局
    horLayout->setContentsMargins(0,0,0,0);
    horLayout->setSpacing(0);
    QPushButton * btnicon = new QPushButton();
    btnicon->setFixedSize(50,50);
    btnicon->setIconSize(QSize(50,50));
    btnicon->setStyleSheet("background:rgba(0,0,0,0);");
    QLabel * label = new QLabel(data);
    //内容换行处理
    int num = data.length()/45;
    for (;num>0;--num) {
        data.insert(num*45,'\n');
    }
    int count = data.count("\n");
    label->setMaximumWidth(700);
    label->setWordWrap(true);
    label->setMaximumHeight((count+2)*30);
    label->setMinimumHeight(70);
    widget->setMaximumHeight((count+4)*30);
    widget->setMinimumHeight(70);
    if(i%2)//对方消息
    {
        label->setFont(font1);
        label->setStyleSheet("background-color: rgb(140, 105, 255);border-style:solid;border-width:2px;border-color: rgb(125, 242, 255);border-radius:10px;");
        label->setTextInteractionFlags(Qt::TextSelectableByMouse);
        label->setAlignment(Qt::AlignCenter|Qt::AlignLeft);
        horLayout->addWidget(btnicon);
        horLayout->addWidget(label);
        horLayout->addStretch();
        QString headpath = OpDb::getInstance().getHeadPath(name);
        btnicon->setIcon(QPixmap(headpath));
    }
    else//我方消息
    {
        label->setFont(font1);
        label->setStyleSheet("background-color: rgb(232, 100, 150);border-style:solid;border-width:2px;border-color: rgb(100, 150, 255);border-radius:10px;");
        label->setTextInteractionFlags(Qt::TextSelectableByMouse);
        label->setAlignment(Qt::AlignCenter|Qt::AlignRight);
        horLayout->addStretch();
        horLayout->addWidget(label);
        horLayout->addWidget(btnicon);
        QString headpath = OpDb::getInstance().getHeadPath(name);
        btnicon->setIcon(QPixmap(headpath));
    }

    widget->setLayout(horLayout);
    return widget;
}

QWidget *QGroupChat::CreateWidgetL_R(int i, QString name, QPixmap pix)
{
    QWidget * widget = new QWidget();
    widget->setStyleSheet("background:rgba(0,0,0,0);");
    widget->setMinimumSize(QSize(400,300));
    widget->setMaximumSize(QSize(400,300));
    QHBoxLayout *horLayout = new QHBoxLayout();//水平布局
    horLayout->setContentsMargins(0,0,0,0);
    horLayout->setSpacing(0);
    QPushButton * btnicon = new QPushButton();
    btnicon->setFixedSize(50,50);
    btnicon->setIconSize(QSize(50,50));
    btnicon->setStyleSheet("background:rgba(0,0,0,0);");
    QLabel * label = new QLabel;
    label->setMaximumSize(QSize(400,300));
    label->setMinimumSize(QSize(400,300));
    label->setPixmap(pix);
    label->setScaledContents(true);
    if(i%2)//对方消息
    {
        horLayout->setAlignment(Qt::AlignCenter|Qt::AlignRight);
        label->setTextInteractionFlags(Qt::TextSelectableByMouse);
        label->setAlignment(Qt::AlignCenter|Qt::AlignLeft);
        horLayout->addWidget(btnicon);
        horLayout->addWidget(label);
        horLayout->addStretch();
        QString headpath = OpDb::getInstance().getHeadPath(name);
        btnicon->setIcon(QPixmap(headpath));

    }
    else//我方消息
    {
        horLayout->setAlignment(Qt::AlignCenter|Qt::AlignRight);
        //label->setTextInteractionFlags(Qt::TextSelectableByMouse);
        label->setAlignment(Qt::AlignCenter|Qt::AlignRight);
        horLayout->addStretch();
        horLayout->addWidget(label);
        horLayout->addWidget(btnicon);
        QString headpath = OpDb::getInstance().getHeadPath(name);
        btnicon->setIcon(QPixmap(headpath));
        horLayout->setAlignment(Qt::AlignCenter|Qt::AlignRight);
    }

    widget->setLayout(horLayout);

    return widget;
}

void QGroupChat::addMsgWidget(QWidget *widget)
{
    ui->verticalLayout->addWidget(widget);
}

void QGroupChat::clearGroupPersonList()
{
    ui->listWidget->clear();
}

void QGroupChat::updateGroupPersonList(QString name, int i)
{
    QList<QListWidgetItem *> list = ui->listWidget->findItems(name,Qt::MatchContains);
    if(i==1)//成员上线
    {
        if(!list.isEmpty())
        {
            list[0]->setBackground(QColor(255,255,255));
        }
    }
    else//成员下线
    {
        if(!list.isEmpty())
        {
            list[0]->setBackground(QColor(200,200,200));
        }
    }
}

void QGroupChat::setGroupNotify(QString msg)
{
    ui->textEdit_2->setText(msg);
}

void QGroupChat::loadGroupChatRecord(QByteArray qba)
{

    QString msg(qba);
    QStringList list = msg.split("\r\n");
    QString self = Widget::getInstance().getName();
    for(int i=0;i<list.size()-1;i+=2)
    {
        QStringList list1 = list[i].split("&");
        if(list1.size()==0)return;
        QString info = list[i+1].replace("わ","");
        QWidget* widget = new QWidget;
        widget->setStyleSheet("background:rgba(0,0,0,0);");
        widget->setMaximumSize(700,80);
        QHBoxLayout *horLayout = new QHBoxLayout();//水平布局
        horLayout->setContentsMargins(0,0,0,0);
        horLayout->setSpacing(0);
        QLabel * label = new QLabel(list1[1]);
        label->setAlignment(Qt::AlignCenter);
        horLayout->addWidget(label);
        widget->setLayout(horLayout);
        addMsgWidget(widget);
        if(list1[0]==self)
        {
            addMsgWidget(CreateWidgetL_R(0,list1[0],info));
        }else
        {
            addMsgWidget(CreateWidgetL_R(1,list1[0],info));
        }
    }
}

void QGroupChat::OnStartFileTrans()
{
    if(m_file.open(QIODevice::ReadOnly))
    {
        while(!m_file.atEnd())
        {
            char buff[1024] = {0};
            m_file.read(buff,1024);
            PDU* pdu = makePDU(0);
            pdu->msgType = GROUP_FILE;
            strcpy(pdu->friendId,m_gid.toStdString().c_str());
            m_sock.write((char*)pdu,pdu->maxSize);
            m_sock.write(buff,1024);
            delete pdu;
            pdu = nullptr;
        }
        m_file.close();
    }
    PDU* pdu = makePDU(0);
    pdu->msgType = GROUP_FILE2;
    m_sock.write((char*)pdu,pdu->maxSize);
    m_timer.stop();
}

void QGroupChat::on_tbtn_biaoqing_clicked()//表情
{
    ExpressionUI& eui = ExpressionUI::getInstance();
    eui.show();
}

void QGroupChat::on_tbtn_close_clicked()
{
    close();
    destroy();
}

void QGroupChat::on_tbtn_min_clicked()
{
    showMinimized();
}

void QGroupChat::on_btn_close_clicked()
{
    close();
    destroy();
}

void QGroupChat::on_btn_send_clicked()//发消息
{
    if(ui->textEdit->toPlainText().length()>1024)
    {
        QMessageBox::information(this,"提示","消息过长");
        return;
    }
    PDU* pdu = makePDU(0);
    pdu->msgType = GROUP_MSG;
    QString gname = ui->group_name->text();
    strcpy(pdu->friendId,gname.toStdString().c_str());
    QString uname = Widget::getInstance().getName();
    userInfo u;
    strcpy(u.name,uname.toStdString().c_str());
    Widget::getInstance().getTcpSocket().write((char*)pdu,pdu->maxSize);
    Widget::getInstance().getTcpSocket().write((char*)&u,sizeof (u));
    QString msg = ui->textEdit->toPlainText();
    Widget::getInstance().getTcpSocket().write(msg.toUtf8(),msg.toUtf8().length()+1);
    QString name = Widget::getInstance().getName();
    addMsgWidget(CreateWidgetL_R(0,name,msg));
    MainUI::getInstance().updateGroupList(u,3,msg,gname);
    ui->textEdit->clear();
    delete pdu;
    pdu = nullptr;
}

void QGroupChat::on_tbtn_invite_clicked()//邀请新成员
{
    QWidget* widget = new QWidget();
    widget->resize(400,800);
    widget->setWindowTitle("邀请新成员");
    QListWidget* listw = new QListWidget(widget);
    listw->resize(350,710);
    listw->move(30,0);
    QListWidget* friendlist = MainUI::getInstance().getFriendList();
    int count =  friendlist->count();
    for(int i=0;i<count;++i)
    {
        QListWidgetItem* item = friendlist->item(i);
        QList<QListWidgetItem *> list = ui->listWidget->findItems(item->text(),Qt::MatchContains);
        QIcon icon = item->icon();
        QString name = item->text();
        if(list.isEmpty())
        {
            listw->addItem(new QListWidgetItem(icon,name));
            QCheckBox* cb = new QCheckBox(widget);
            QString s = QString("%1").arg(i);
            cb->setWhatsThis(s);
            cb->move(5,i*25);
            cb->resize(30,30);
            cb->show();
            m_checkboxlist.append(cb);
        }
        else
        {
            listw->addItem(new QListWidgetItem(icon,name));
            QCheckBox* cb = new QCheckBox(widget);
            QString s = QString("%1").arg(i);
            cb->setWhatsThis(s);
            cb->setChecked(true);
            cb->setEnabled(false);
            cb->move(5,i*25);
            cb->resize(30,30);
            cb->show();
            m_checkboxlist.append(cb);
        }
    }
    QPushButton* btn = new QPushButton(widget);
    btn->move(180,730);
    btn->resize(80,40);
    btn->setText("确定邀请");
    btn->show();
    connect(btn,&QPushButton::clicked,[=](){
        for(auto x : m_checkboxlist)
        {
            if(x->checkState()==Qt::Checked)
            {
                int n = x->whatsThis().toInt();
                QString recvobj = listw->item(n)->text();//获取接收人账号
                int i = recvobj.indexOf('(');
                recvobj =recvobj.replace(")","");
                recvobj = recvobj.mid(i+1);
                qDebug()<<recvobj;
                QString recvobj2 = ui->group_name->text();//获取群账号
                i = recvobj2.indexOf('(');
                recvobj2 =recvobj2.replace(")","");
                recvobj2 = recvobj2.mid(i+1);
                qDebug()<<recvobj2;
                PDU* pdu = makePDU(0);
                pdu->msgType = GROUP_ADDPERSON;
                strcpy(pdu->friendId,recvobj.toStdString().c_str());
                strcpy(pdu->data,recvobj2.toStdString().c_str());
                Widget::getInstance().getTcpSocket().write((char*)pdu,pdu->maxSize);
                QString iconpath =  OpDb::getInstance().getHeadPath(recvobj);
                ui->listWidget->addItem(new QListWidgetItem(QIcon(iconpath),recvobj));
                delete pdu;
                pdu = nullptr;
            }
        }
    });
    listw->show();
    widget->show();
}

void QGroupChat::on_toolButton_clicked()
{
    ui->group_name_2->setEnabled(true);
    ui->group_name_2->setText(ui->group_name->text());
    ui->group_name_2->selectAll();
    ui->group_name->hide();
}

void QGroupChat::on_tbtn_jietu_clicked()
{
    QProcess pro(this);
    pro.startDetached(QString("D:\\QTCode5.14\\CClient\\release\\截图.exe"));
}

void QGroupChat::on_group_name_2_editingFinished()
{
    ui->group_name->setText(ui->group_name_2->text());
    ui->group_name_2->setEnabled(false);
    ui->group_name->show();
    ui->group_name_2->setText("");
}

void QGroupChat::on_toolButton_2_clicked()
{
    ui->textEdit_2->setReadOnly(false);
}

void QGroupChat::on_pushButton_2_clicked()//发布群公告
{
    QString text = ui->textEdit_2->toPlainText();
    PDU* pdu = makePDU(0);
    pdu->msgType = GROUP_NOTIFY;
    QString recvobj2 = ui->group_name->text();//获取群账号
    int i = recvobj2.indexOf('(');
    recvobj2 =recvobj2.replace(")","");
    recvobj2 = recvobj2.mid(i+1);
    strcpy(pdu->friendId,recvobj2.toStdString().c_str());
    Widget::getInstance().getTcpSocket().write((char*)pdu,pdu->maxSize);
    delete pdu;
    pdu = nullptr;
    Widget::getInstance().getTcpSocket().write(text.toUtf8(),text.toUtf8().length());
    ui->textEdit_2->setReadOnly(true);
}

void QGroupChat::on_tbtn_new_clicked()//获取聊天记录
{
    QString recvobj2 = ui->group_name->text();//获取群账号
    int i = recvobj2.indexOf('(');
    recvobj2 =recvobj2.replace(")","");
    recvobj2 = recvobj2.mid(i+1);
    PDU* pdu = makePDU(0);
    pdu->msgType = LOAD_GROUP_RECORD;
    strcpy(pdu->friendId,recvobj2.toStdString().c_str());
    Widget::getInstance().getTcpSocket().write((char*)pdu,pdu->maxSize);
    delete pdu;
    pdu = nullptr;
}

void QGroupChat::on_pushButton_clicked()//上传文件
{
//    m_filename = QFileDialog::getOpenFileName(this,tr("选择文件"), "C:", tr("所有文件 (*.*)\r\n图片 (*.png *.jpg *.bmp,&.jpeg)\r\n文本文件 (*.txt)"));
//    m_file.setFileName(m_filename);
//    QFileInfo innfo(m_filename);
//    QString str = QString("%1").arg(innfo.fileName());
//    PDU* pdu = makePDU(0);
//    pdu->msgType = GROUP_FILE3;
//    strcpy(pdu->friendId,m_gid.toStdString().c_str());
//    m_sock.write((char*)pdu,pdu->maxSize);
//    m_sock.write(str.toUtf8(),str.toUtf8().length());
//    m_timer.start(100);
}
